package com.archstoday.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.adapter.SchemeDetailImageAdapter;
import com.archstoday.adapter.StringTagAdapter;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.EngineesDetailsEntity;
import com.archstoday.entity.SchemeDetailEntity;
import com.archstoday.entity.ShareEntity;
import com.archstoday.event.MessageRefreshSchemeEvent;
import com.archstoday.textview.ActionMenu;
import com.archstoday.textview.CustomActionMenuCallBack;
import com.archstoday.textview.SelectableTextView;
import com.archstoday.utils.AppUtils;
import com.archstoday.utils.CustomVerticalCenterSpan;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.ProcessUtils;
import com.archstoday.utils.RxTimeUtils;
import com.archstoday.utils.ToolUtils;
import com.archstoday.utils.WechatUtils;
import com.archstoday.view.AutoNewLineLayout;
import com.archstoday.view.RecycleViewDivider;
import com.base.http.common.BaseHttpClient;
import com.base.utils.ImageUtil;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.shuyu.action.web.ActionSelectListener;
import com.shuyu.action.web.CustomActionWebView;
import com.tools.app.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import de.hdodenhof.circleimageview.CircleImageView;
import zhouyou.flexbox.interfaces.OnFlexboxSubscribeListener;
import zhouyou.flexbox.widget.TagFlowLayout;

/**
 * 方案详情页面
 */
public class SchemeDetailActivity extends AsBaseActivity {
        //implements CustomActionMenuCallBack {

    private TextView mTitleTv;
    private TextView mDetailsTitleTv, mFromeTv, mTypeTv, mDesTv, mReadBtn, mLikeBtn, mFocusBtn;
    private CircleImageView mUserHead;
    private ImageButton mDownload;
//    private SelectableTextView mSumary;
    private CustomActionWebView mWebView;
    private TextView mSchemeComments;
    private TextView mSchemeImage;
    private AutoNewLineLayout mKeywordLayout;
    RecyclerView mImageRecyclerView;
    RecyclerView mTagsRecyclerView;

    TagFlowLayout flowLayout;

    private int articleID;
    private String mChannel;

    private SchemeDetailEntity mSchemeEntity;
    private String mAction;

    SchemeDetailImageAdapter schemeDetailImageAdapter;

    List<String> list;
    ArrayList<String> listImages;


    private String mFocusAction;


    private MyTimeTask mTimeTask;
    private Timer timer;
    private int recLen;

    class MyTimeTask extends TimerTask {
        @Override
        public void run() {
            Message message = new Message();
            handler.sendMessage(message);
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            if(recLen == 0){
                mLikeBtn.setEnabled(true);
            }
            recLen--;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mTimeTask != null) {
            mTimeTask.cancel();
        }
    }

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_scheme_details);
        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mDetailsTitleTv = (TextView) findViewById(R.id.details_title_tv);
        mTypeTv = (TextView) findViewById(R.id.scheme_type_tv);
        mFromeTv = (TextView) findViewById(R.id.details_from_tv);
        mDesTv = (TextView) findViewById(R.id.details_des_tv);
//        mSumary = (SelectableTextView) findViewById(R.id.id_for_summary);
        mWebView = (CustomActionWebView) findViewById(R.id.summary_web_view);
        mReadBtn = (TextView) findViewById(R.id.details_previewbtn);
        mLikeBtn = (TextView) findViewById(R.id.details_like_btn);
        mFocusBtn = (TextView) findViewById(R.id.id_for_focus);
        mDownload = (ImageButton) findViewById(R.id.details_download_btn);
//        mSumary.setCustomActionMenuCallBack(this);

        mUserHead = (CircleImageView) findViewById(R.id.scheme_user_icon);
        mSchemeComments = (TextView) findViewById(R.id.details_discussion_btn);
        mSchemeImage = (TextView) findViewById(R.id.id_for_scheme_image);
        flowLayout = (TagFlowLayout) findViewById(R.id.id_for_scheme_tag_flow_layout);
        mKeywordLayout = (AutoNewLineLayout) findViewById(R.id.id_source_keyword);

        // 显示图片
        mImageRecyclerView = (RecyclerView) findViewById(R.id.id_for_detail_image);

        mImageRecyclerView.setHasFixedSize(true);
        mImageRecyclerView.setNestedScrollingEnabled(false);//解决触摸到RecyclerView的时候滑动还有些粘连的感觉
        mImageRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL, AppUtils.dip2px(mContext, 6f), R.color.colorPrimaryDark));

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mImageRecyclerView.setLayoutManager(linearLayoutManager);

        mImageRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {

            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });

        schemeDetailImageAdapter = new SchemeDetailImageAdapter(listImages, mContext);
        mImageRecyclerView.setAdapter(schemeDetailImageAdapter);
    }

    @Override
    protected void initData(Bundle bundle) {
        EventBus.getDefault().register(this);

        list = new ArrayList<>();
        list.add("拷贝");
        list.add("分享文字");
        initSetting();

        listImages = new ArrayList<>();

        mTitleTv.setText("方案详情");
        mReadBtn.setVisibility(View.GONE);
        articleID = getIntent().getIntExtra("id", 0);
        upNewsData();
    }

    private void initSetting() {
        WebSettings ws = mWebView.getSettings();
//        ws.setBuiltInZoomControls(false);
//        ws.setSupportZoom(false);
        ws.setJavaScriptEnabled(true);
//        ws.setAllowFileAccess(true);
//        ws.setSupportMultipleWindows(true);
//        ws.setJavaScriptCanOpenWindowsAutomatically(true);
//        ws.setLoadsImagesAutomatically(true);
//        ws.setDomStorageEnabled(true);
//        ws.setDisplayZoomControls(false);
//        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        ws.setUseWideViewPort(true);
//        ws.setLoadWithOverviewMode(false);
        mWebView.setWebChromeClient(new WebChromeClient());

        mWebView.setWebViewClient(new CustomWebViewClient());

        //设置item
        mWebView.setActionList(list);

        //链接js注入接口，使能选中返回数据
        mWebView.linkJSInterface();

//        mWebView.getSettings().setBuiltInZoomControls(true);
//        mWebView.getSettings().setDisplayZoomControls(false);
        //使用javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);

        //增加点击回调
        mWebView.setActionSelectListener(new ActionSelectListener() {

            @Override
            public void onClick(String title, String selectText) {
                Log.e("onClick", "onClick--");

                if (title.equalsIgnoreCase("分享文字")) {
                    Intent intent = new Intent();
                    intent.putExtra("id", articleID);
                    intent.putExtra("content", selectText);
                    intent.putExtra("type", "solution");
                    intent.putExtra("categoryId1", mSchemeEntity.getData().getCategoryId1());

                    intent.setClass(mContext, TextShareActivity.class);
                    startActivity(intent);
                }

                if (title.equalsIgnoreCase("拷贝")) {
                    ToolUtils.copyUrl(mContext, selectText);
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.dismissAction();
        }
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.back_btn);
        setOnClickListener(R.id.details_previewbtn);
        setOnClickListener(R.id.details_download_btn);
        setOnClickListener(R.id.details_discussion_btn);
        setOnClickListener(R.id.details_share_btn);
        setOnClickListener(R.id.details_like_btn);
        setOnClickListener(R.id.id_for_focus);
    }

    @Override
    public void treatClickEvent(int id) {
        Map<String, String> info;
        switch (id) {
            case R.id.back_btn:
                appFinish();
                break;
            case R.id.details_download_btn:
                if (!StringUtil.isEmpty(mSchemeEntity.getData().getSourceDetailLink())) {
                    info = new HashMap<>();
                    info.put("articleId", String.valueOf(mSchemeEntity.getData().getArticleId()));
                    info.put("categoryId1", String.valueOf(mSchemeEntity.getData().getCategoryId1()));
                    info.put("isFree", String.valueOf(mSchemeEntity.getData().getIsFree()));
                    getEvent(BaseApp.E_PREVIEW, BaseApp.PAGE_TYPE_PREVIEW,
                            ToolUtils.mapToJson(info));

                    String sourceDetailLink = mSchemeEntity.getData().getSourceDetailLink();

                    //跳转河姆渡的官网
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(sourceDetailLink);
                    intent.setData(content_url);
                    startActivity(intent);
                }

                break;

            case R.id.details_previewbtn:
//                if (!ToolUtils.isWifiConnected(mContext)) {
//                    showToast("请在wifi环境下查看");
//                    return;
//                }
                info = new HashMap<>();
                info.put("articleId", String.valueOf(mSchemeEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mSchemeEntity.getData().getCategoryId1()));
                info.put("isFree", String.valueOf(mSchemeEntity.getData().getIsFree()));
                getEvent(BaseApp.E_PREVIEW, BaseApp.PAGE_TYPE_PREVIEW,
                        ToolUtils.mapToJson(info));

                if (!StringUtil.isEmpty(mSchemeEntity.getData().getAttachment())) {
                    if (ToolUtils.isPermission(mContext)) {
                        String pdfAddress = mSchemeEntity.getData().getAttachment();
                        if (pdfAddress.indexOf(",") > 0) {
                            pdfAddress = pdfAddress.substring(pdfAddress.indexOf("[") + 1, pdfAddress.indexOf(","));
                        } else {
                            if (pdfAddress.indexOf("[") > 0) {
                                pdfAddress = pdfAddress.substring(pdfAddress.indexOf("[") + 1, pdfAddress.indexOf("]"));
                            }
                        }

                        Intent intent = new Intent(mContext, DownloadPdfActivity.class);
                        intent.putExtra("web", mSchemeEntity.getData().getSourceDetailLink());
                        intent.putExtra("isFree", mSchemeEntity.getData().getIsFree());
                        intent.putExtra("url", pdfAddress);
                        startActivity(intent);
                    } else {
                        ToolUtils.getAppDetailSettingIntent(mContext);
                    }
                } else if (!StringUtil.isEmpty(mSchemeEntity.getData().getSourceDetailLink())) {
                    Intent intent = new Intent(mContext, WebActivity.class);
                    intent.putExtra("url", mSchemeEntity.getData().getAttachment());
                    startActivity(intent);
                }
//                }
                break;
            case R.id.details_share_btn:
                setDialog();
                break;
            case R.id.share_wx_btn:
                info = new HashMap<>();
                info.put("articleId", String.valueOf(mSchemeEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mSchemeEntity.getData().getCategoryId1()));
                info.put("channel", "wechat");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));

                mChannel = "wechat";
                share();
                break;
            case R.id.share_group_btn:
                info = new HashMap<>();
                info.put("articleId", String.valueOf(mSchemeEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mSchemeEntity.getData().getCategoryId1()));
                info.put("channel", "friends");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));


                mChannel = "friends";
                share();
                break;
            case R.id.share_link_btn:
                info = new HashMap<>();
                info.put("articleId", String.valueOf(mSchemeEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mSchemeEntity.getData().getCategoryId1()));
                info.put("channel", "link");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));


                mChannel = "msg";
                share();
                break;
            case R.id.details_like_btn:
                if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
                    showToast(R.string.user_userid_null);

                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                    appFinish();
                } else {
                    info = new HashMap<>();
                    info.put("articleId", String.valueOf(mSchemeEntity.getData().getArticleId()));
                    info.put("categoryId1", String.valueOf(mSchemeEntity.getData().getCategoryId1()));
                    getEvent(BaseApp.E_FAV, BaseApp.PAGE_TYPE_FAV,
                            ToolUtils.mapToJson(info));

                    if (mLikeBtn.isSelected()) {
                        mAction = "del";
                        like();
                    } else {
                        mAction = "add";
                        like();
                    }

                    mLikeBtn.setEnabled(false);
                    timer = new Timer();
                    mTimeTask = new MyTimeTask();
                    recLen = 1;
                    timer.schedule(mTimeTask, 1000, 1000);
                }
                break;

            case R.id.details_discussion_btn:
                if (mSchemeEntity == null) {
                    return;
                }
                info = new HashMap<>();
                info.put("articleId", String.valueOf(mSchemeEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mSchemeEntity.getData().getCategoryId1()));
                getEvent(BaseApp.E_COMMENT, BaseApp.PAGE_TYPE_COMMENT,
                        ToolUtils.mapToJson(info));

                Intent specialIntent = new Intent();
//                specialIntent.putExtra("data", mSchemeEntity);
                specialIntent.putExtra("articleId", mSchemeEntity.getData().getArticleId());
                specialIntent.putExtra("categoryId1", mSchemeEntity.getData().getCategoryId1());
                specialIntent.setClass(mContext, SpecialCommentActivity.class);
                startActivity(specialIntent);
                break;
            case R.id.id_for_focus:
                if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
                    showToast(R.string.user_userid_null);

                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivity(loginIntent);
                    appFinish();
                } else {
                    if (mSchemeEntity == null) {
                        return;
                    }
                    if (mSchemeEntity.getData().getIsArticleUserLiked() == 1) {
                        mFocusAction = "del";
                        focus();
                    } else {
                        mFocusAction = "add";
                        focus();
                    }
                }
                break;
        }
    }

    private void addKeyword(String str) {
        List<String> data = new ArrayList<>();
        while (str.indexOf(",") > -1) {
            data.add(str.substring(0, str.indexOf(",")));
            str = str.substring(str.indexOf(",") + 1);
        }
        if (!StringUtil.isEmpty(str)) {
            data.add(str);
        }

        mKeywordLayout.removeAllViews();
        for (int i = 0; i < data.size(); i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_keyword, null);
            TextView history = (TextView) view.findViewById(R.id.item_tv);

            history.setText(data.get(i));
            history.setTag(data.get(i));
            history.setBackgroundResource(R.drawable.details_btn);
            history.setOnClickListener(click);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                    (LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            params.rightMargin = (int) getResources().getDimension(R.dimen.dp10);
            mKeywordLayout.addView(view, params);
        }
    }

    private void focus() {
        initParameter();
        mParams.put("userIdLiked", mSchemeEntity.getData().getUserId());
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", mApp.getDeviceID(mContext));
        mParams.put("action", mFocusAction);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.FOCUS_AUTHOR),
                AsRes.FOCUS_AUTHOR, mParams, BaseEntity.class);
    }

    private void like() {
        initParameter();
        mParams.put("articleId", String.valueOf(articleID));
        mParams.put("categoryId1", mSchemeEntity.getData().getCategoryId1());
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", mApp.getDeviceID(mContext));
        mParams.put("action", mAction);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.EDIT_LIKE),
                AsRes.EDIT_LIKE, mParams, BaseEntity.class);
    }

    private void upNewsData() {
        initParameter();
        mParams.put("id", articleID);
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("toke", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_SCHEME_DETAIL),
                AsRes.GET_SCHEME_DETAIL, mParams, SchemeDetailEntity.class);
    }

    private void upEgData() {
        initParameter();
        mParams.put("id", articleID);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_SCHEME_DETAIL),
                AsRes.GET_SCHEME_DETAIL, mParams, EngineesDetailsEntity.class);
    }

    private void share() {
        initParameter();
        mParams.put("articleID", articleID);
        mParams.put("channel", mChannel);
        mParams.put("type", "solution");

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.SHARE),
                AsRes.SHARE, mParams, ShareEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        if (client.getUrlIdentifier() == AsRes.GET_SCHEME_DETAIL) {
            mSchemeEntity = (SchemeDetailEntity) parse;
            if (ToolUtils.isSuccess(mSchemeEntity.getStatus())) {
                if (mSchemeEntity.getData().getIsFree() != 1) {
                    String title = " 付费  " + mSchemeEntity.getData().getTitle();
                    mDetailsTitleTv.setBackgroundColor(ImageUtil.getColor(mContext, R.color.red));

                    SpannableString msp = new SpannableString(title);
//                    msp.setSpan(new RelativeSizeSpan(0.8f), 0, 4,
//                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    msp.setSpan(new CustomVerticalCenterSpan(mContext, 14), 0, 4,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//                    msp.setSpan(new ForegroundColorSpan(Color.WHITE), 0, 4,
//                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    msp.setSpan(new BackgroundColorSpan(Color.WHITE), 4, title.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    mDetailsTitleTv.setText(msp);
                } else {
                    mDetailsTitleTv.setText(mSchemeEntity.getData().getTitle());
                }
                ImageUtil.setCropBitmap(mContext, mUserHead,
                        mSchemeEntity.getData().getUserImg(), R.mipmap.user_header_icon);
                mFromeTv.setText(mSchemeEntity.getData().getUserName());

                SimpleDateFormat DEFAULT_SDF = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
                String time = mSchemeEntity.getData().getUpdateTime();
                time = RxTimeUtils.milliseconds2String(RxTimeUtils.string2Milliseconds(time), DEFAULT_SDF);

                addKeyword(mSchemeEntity.getData().getSourceKeyword());

                mDesTv.setText(ProcessUtils.procesText(time));
                mSchemeComments.setText(String.valueOf(mSchemeEntity.getData().getComments()));

                mLikeBtn.setText(String.valueOf(mSchemeEntity.getData().getLikes()));
                mLikeBtn.setSelected(mSchemeEntity.getData().getIslike() == 1 ? true : false);
//                if (mSchemeEntity.getData().getIslike() == 0) {
//                    mLikeBtn.setTextColor(mContext.getResources().getColor(R.color.black));
//                } else {
//                    mLikeBtn.setTextColor(mContext.getResources().getColor(R.color.scheme_yellow));
//                }
                if (mSchemeEntity.getData().getIsArticleUserLiked() == 0) {
                    mFocusBtn.setText("关注");
                    mFocusBtn.setTextColor(mContext.getResources().getColor(R.color.white));
                    mFocusBtn.setBackgroundColor(mContext.getResources().getColor(R.color.green_text));
                } else {
                    mFocusBtn.setText("已关注");
                    mFocusBtn.setTextColor(mContext.getResources().getColor(R.color.black));
                    mFocusBtn.setBackground(mContext.getResources().getDrawable(R.drawable.topic_has_focus));
                }
//                mTypeTv.setText(mSchemeEntity.getData().getIsFree() == 1 ? "免费资源" : "付费精品");

                if (mSchemeEntity.getData().getAttachment() != null) {
                    mReadBtn.setVisibility(View.VISIBLE);
                }

//                mSumary.setText(ProcessUtils.procesText(mSchemeEntity.getData().getSummary()));
                mWebView.loadDataWithBaseURL(null,
                        ProcessUtils.procesText(mSchemeEntity.getData().getSummary()), "text/html", "utf-8", null);

                listImages.clear();
                if (mSchemeEntity.getData().getImgs() != null) {
                    String[] imgs = mSchemeEntity.getData().getImgs().split(",");
                    for (int i = 0; i < imgs.length; i++) {
                        listImages.add(imgs[i]);
                    }
                }

                if (listImages != null && listImages.size() > 0) {
                    mSchemeImage.setVisibility(View.VISIBLE);
                    schemeDetailImageAdapter.setNewData(listImages);
                } else {
                    mSchemeImage.setVisibility(View.GONE);
                }

                initSchemeTags(mSchemeEntity.getData().getSourceKeyword());
            } else {
                showToast(mSchemeEntity.getMsg());
            }

        } else if (client.getUrlIdentifier() == AsRes.SHARE) {
            ShareEntity entity = (ShareEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                getEvent(mApp.E_SHARE, mApp.PAGE_TYPE_SHARE);
                switch (mChannel) {
                    case "wechat":
                        WechatUtils.share(mContext, entity.getData().getTitel(),
                                entity.getData().getDesp(), entity.getData().getUrl(),
                                false);
                        break;
                    case "friends":
                        WechatUtils.share(mContext, entity.getData().getTitel(),
                                entity.getData().getDesp(), entity.getData().getUrl(),
                                true);
                        break;
                    case "msg":
                        ToolUtils.copyUrl(mContext, entity.getData().getUrl());
                        break;
                }
                dismissShare();
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.EDIT_LIKE) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                switch (mAction) {
                    case "add":
                        mLikeBtn.setText(String.valueOf(mSchemeEntity.getData().getLikes() + 1));
                        mSchemeEntity.getData().setLikes(mSchemeEntity.getData().getLikes() + 1);
                        break;
                    case "del":
                        mLikeBtn.setText(String.valueOf(mSchemeEntity.getData().getLikes() - 1));
                        mSchemeEntity.getData().setLikes(mSchemeEntity.getData().getLikes() - 1);
                        break;
                }
                mLikeBtn.setSelected(!mLikeBtn.isSelected());
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.FOCUS_AUTHOR) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                switch (mFocusAction) {
                    case "add":
                        mFocusBtn.setText("已关注");
                        mFocusBtn.setTextColor(mContext.getResources().getColor(R.color.black));
                        mFocusBtn.setBackground(mContext.getResources().getDrawable(R.drawable.topic_has_focus));

                        mSchemeEntity.getData().setIsArticleUserLiked(1);
                        break;
                    case "del":
                        mFocusBtn.setText("关注");
                        mFocusBtn.setTextColor(mContext.getResources().getColor(R.color.white));
                        mFocusBtn.setBackgroundColor(mContext.getResources().getColor(R.color.green_text));

                        mSchemeEntity.getData().setIsArticleUserLiked(0);
                        break;
                }
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            } else {
                showToast(entity.getMsg());
            }
        }
    }

    private void initSchemeTags(String tags) {
        if (TextUtils.isEmpty(tags)) {
            return;
        }

        List<String> defList = new ArrayList<>();
        String[] tagList = tags.split(",");
        for (int i = 0; i < tagList.length; i++) {
            defList.add(tagList[i]);
        }

        //设置头部评论
        StringTagAdapter adapter = new StringTagAdapter(mContext, defList, defList);
        adapter.setOnSubscribeListener(new OnFlexboxSubscribeListener<String>() {

            @Override
            public void onSubscribe(List<String> selectedItem) {
                LogUtil.error("");

            }
        });

        flowLayout.setAdapter(adapter);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageRefreshSchemeEvent event) {
        upNewsData();
    }

    private class CustomWebViewClient extends WebViewClient {

        private boolean mLastLoadFailed = false;

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            if (!mLastLoadFailed) {
                CustomActionWebView customActionWebView = (CustomActionWebView) webView;
                customActionWebView.linkJSInterface();
            }
        }

        @Override
        public void onPageStarted(WebView webView, String url, Bitmap favicon) {
            super.onPageStarted(webView, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLastLoadFailed = true;
        }
    }

//    @Override
//    public boolean onCreateCustomActionMenu(ActionMenu menu) {
//        return false;
//    }
//
//    @Override
//    public void onCustomActionItemClicked(String itemTitle, String selectedContent) {
//        Intent intent = new Intent();
//        intent.putExtra("id", articleID);
//        intent.putExtra("content", selectedContent);
//        intent.putExtra("type", "solution");
//        intent.putExtra("categoryId1", mSchemeEntity.getData().getCategoryId1());
//
//        intent.setClass(mContext, TextShareActivity.class);
//        startActivity(intent);
//    }
}